package com.hz.house.service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.hz.house.token.JWTUtil;
import com.hz.house.token.UaaClaims;

/**
 * <p> 统计业务
 * @author lfw
 *
 */
@Service
public class StatisticsService {
	
	//使用此线程池进行统计相关处理
	private ExecutorService es = Executors.newFixedThreadPool(2);
	
	@Autowired
	private RedisTemplate<String,Object> redis;
	
	/**
	 * <p> 进行统计
	 * @param header
	 * @param url
	 */
	public void doStatisticsVisits(String token,String url) {
		
		Integer userid = getUserId(token);
		if(userid==null)
			return;
		
		//统计单日单用户的访问量
		perDayPerUserVisits(userid);
		
		//记录用户最后
		
	}
	
	private Integer getUserId(String token) {
		Integer userid = null;
		try {
			UaaClaims res = JWTUtil.validate(token);
			if(res==null)
				return null;
			String uid = res.getUserId();
			userid = Integer.parseInt(uid);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return userid;
	}
	
	

	/**
	 * <p> 单日单次单人的访问量统计，基于redis缓存并每日0时同步到数据库
	 * @param userid
	 */
	private void perDayPerUserVisits(Integer userid) {
		
		es.execute(()->{
			//通过set的特性 进行重复过滤
			redis.opsForSet().add("statistics_visits_per_day_per_user", userid);
		});
	}
	
}
